package com.tjjingpan.wifidirectdemo.utils

import android.annotation.SuppressLint
import android.content.Context
import android.net.wifi.WpsInfo
import android.net.wifi.p2p.*
import android.net.wifi.p2p.WifiP2pManager.ActionListener
import android.os.Looper
import kotlin.properties.Delegates

import android.util.Log

import com.tjjingpan.wifidirectdemo.callback.DirectActionListener
import com.tjjingpan.wifidirectdemo.DeviceAdapter
import com.tjjingpan.wifidirectdemo.R
import com.tjjingpan.wifidirectdemo.adapter.WifiDirectDeviceAdapter
import com.tjjingpan.wifidirectdemo.model.WiFiDirectDevice
import com.tjjingpan.wifidirectdemo.test.Fruit
import com.tjjingpan.wifidirectdemo.test.FruitAdapter
import java.lang.StringBuilder


//https://blog.csdn.net/qq_33215972/article/details/79762504
object WifiDirectManager {
    val TAG = "WifiDirectManager"
    var manager :WifiP2pManager by Delegates.notNull()
    var channel:WifiP2pManager.Channel by Delegates.notNull()
    var wifiP2pEnabled = false
    var wifiP2pDeviceList: Collection<WifiP2pDevice>? = null


//    private val fruitList = ArrayList<Fruit>()
//    var adapter = FruitAdapter(fruitList)

    private val wifiDirectDeviceList = ArrayList<WiFiDirectDevice>()
    var deviceAdapter = WifiDirectDeviceAdapter(wifiDirectDeviceList)


    val directActionListener =object:  DirectActionListener {
        override fun wifiP2pEnabled(enabled: Boolean) {
            Log.e(TAG,"wifiP2pEnabled")
            wifiP2pEnabled = enabled
        }

        override fun onConnectionInfoAvailable(wifiP2pInfo: WifiP2pInfo) {
            wifiP2pDeviceList= null
            Log.e(TAG, "onConnectionInfoAvailable")
            Log.e(TAG, "onConnectionInfoAvailable groupFormed: " + wifiP2pInfo.groupFormed)
            Log.e(TAG, "onConnectionInfoAvailable isGroupOwner: " + wifiP2pInfo.isGroupOwner)
            Log.e(TAG, "onConnectionInfoAvailable getHostAddress: " + wifiP2pInfo.groupOwnerAddress.hostAddress
            )
            val stringBuilder = StringBuilder()

        }

        override fun onDisconnection() {
            Log.e(TAG,"onDisconnection")
        }

        override fun onSelfDeviceAvailable(wifiP2pDevice: WifiP2pDevice) {
           Log.e(TAG,"onSelfDeviceAvailable")
        }

        @SuppressLint("NotifyDataSetChanged")
        override fun onPeersAvailable(wifiP2pDeviceList: MutableCollection<WifiP2pDevice>) {
            Log.e(TAG,"onPeersAvailable")
            Log.d(TAG, "wifiP2pDeviceList$wifiP2pDeviceList")
            Log.d(TAG, "wifiP2pDeviceList:${wifiP2pDeviceList.size}")
            if(wifiP2pDeviceList.size >= 1 ){
                for(device in wifiP2pDeviceList){
                    val deviceName = device.deviceName
                    val deviceAddress= device.deviceAddress
                    val status= device.status
                    wifiDirectDeviceList.add(WiFiDirectDevice(deviceName,deviceAddress,status))
                }

            }else{
                Log.d(TAG,"没有获取到p2p设备")
                wifiDirectDeviceList.clear()
            }
            Log.d(TAG,"peersshowlist显示列表数量:${wifiDirectDeviceList.size}")

//            initFruits()
//            adapter.notifyDataSetChanged()

            //initWifiDirectList()
            deviceAdapter.notifyDataSetChanged()
        }

        override fun onChannelDisconnected() {
            Log.e(TAG,"onChannelDisconnected")
        }

    }


    fun init(context:Context):WifiDirectManager{
        //通过获取系统服务的方式获得Manager对象
        manager = context.getSystemService(Context.WIFI_P2P_SERVICE) as WifiP2pManager
//        channel = manager.initialize(context, Looper.getMainLooper()){
//            //初始化操作成功的回调
//            Log.d(TAG,"//初始化操作成功的回调")
//        }
        channel = manager.initialize(context, Looper.getMainLooper(), directActionListener)
        return this
    }

    /**
     * discover available peer list
     */
    @SuppressLint("MissingPermission")
    fun discoverPeers(): WifiDirectManager {
        manager.discoverPeers(channel, object : ActionListener{
            override fun onSuccess() {
                println("discover Peers success")
            }

            override fun onFailure(reason: Int) {
                println("discover Peers fail: $reason")
            }
        })
        return this
    }

    /**
     * request the peer list available
     */
    @SuppressLint("MissingPermission")
    fun requestPeers(): WifiDirectManager {
        manager.requestPeers(channel) { peers ->
            //请求对等节点列表操作成功
            Log.d(TAG,peers.toString())
        }
        return this
    }

    /**
     * connect by MAC address(hardware address)
     */
    @SuppressLint("MissingPermission")
    fun connect(deviceAddress: String) {
        val config = WifiP2pConfig()
        config.deviceAddress = deviceAddress
        config.wps.setup = WpsInfo.PBC
        manager.connect(channel, config, object : ActionListener {
            override fun onSuccess() {
                println("connect operator success")
            }

            override fun onFailure(reason: Int) {
                println("connect operator fail: $reason")
            }
        })
    }

    /**
     * invoke this method to connect a p2p device
     */
    fun connect(device: WifiP2pDevice): WifiDirectManager {
        connect(device.deviceAddress)
        return this
    }

    @SuppressLint("MissingPermission")
    fun createGroup(){
        manager.createGroup(channel,object :ActionListener{
            override fun onSuccess() {
                Log.d(TAG,"CreateGroup OnSuccess")
            }

            override fun onFailure(p0: Int) {
                Log.d(TAG,"CreateGroup onFailure")
            }
        })
    }
    @SuppressLint("MissingPermission")
    fun removeGroup(){
        manager.removeGroup(channel,object :ActionListener{
            override fun onSuccess() {
                Log.d(TAG,"removeGroup OnSuccess")
            }

            override fun onFailure(p0: Int) {
                Log.d(TAG,"removeGroup onFailure")
            }
        })
    }

    /**
     * request the group info
     */
    @SuppressLint("MissingPermission")
    fun requestGroup(): WifiDirectManager {
        manager.requestGroupInfo(channel) { group ->
            Log.d(TAG,group.clientList.toString())
        }
        return this
    }


//
//    private fun initFruits() {
//        repeat(2) {
//            fruitList.add(Fruit("Apple", R.drawable.apple_pic))
//            fruitList.add(Fruit("Banana", R.drawable.banana_pic))
//            fruitList.add(Fruit("Orange", R.drawable.orange_pic))
//            fruitList.add(Fruit("Watermelon", R.drawable.watermelon_pic))
//            fruitList.add(Fruit("Pear", R.drawable.pear_pic))
//            fruitList.add(Fruit("Grape", R.drawable.grape_pic))
//            fruitList.add(Fruit("Pineapple", R.drawable.pineapple_pic))
//            fruitList.add(Fruit("Strawberry", R.drawable.strawberry_pic))
//            fruitList.add(Fruit("Cherry", R.drawable.cherry_pic))
//            fruitList.add(Fruit("Mango", R.drawable.mango_pic))
//        }
//    }

    private fun initWifiDirectList(){
        wifiDirectDeviceList.add(WiFiDirectDevice("android1","abc",2))
        wifiDirectDeviceList.add(WiFiDirectDevice("android2","abd",1))
        wifiDirectDeviceList.add(WiFiDirectDevice("android3","abe",2))
    }
}